/* eslint-disable prettier/prettier */
import { Breadcrumb, Space, Button, Table, Tabs, message, Modal, TableProps } from 'antd';
import React, { FC } from 'react';
import {
  FormPanel,
  type FormPanelObject,
  FormPanelBtnAlign,
  InputType,
  RuleType,
  ExtendReader,
  FormPanelBtnDisplay,
  Utils,
} from 'lfun-bg-comp';
import _ from 'lodash';
import { useNavigate } from 'react-router-dom';
import { PageContainer } from '@/component/page-container';
import { SearchTransactionParams, Transaction } from '@/service/teacher/transaction';
import { PageParams } from '@/service';
import { PAGINATIONCONFIG } from '@/constant/page';
import { ID_TYPE } from '@/constant/studentOptions';
import { GENDER } from '@/constant/basicOptions';
import { getProvinceCityCascader } from '@/service/options';
import { APPROVAL_STATUS } from '@/constant';
import { getPathRoot, get_stoge_pz, set_stoge_pz } from '@/utils';
import { borrowRevoked, searchBorrowOutApproval, searchBorrowOutLaunch } from '@/service/teacher/borrow';
import BorrowPopup from './op/borrowPopup';
import styles from './index.less';
import { transferApproved, transferRejected } from '@/service/teacher/transfer';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';
import useCountry from '@/hooks/useCountry';
import dayjs from 'dayjs';

const Groups: FC = () => {
  const navigator = useNavigate();
  const [dataSource, setDataSource] = React.useState<Transaction[]>([]);
  const [loading, setLoading] = React.useState(false);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz());
  const [pageIndex, setPageIndex] = React.useState(1);
  const [form, setForm] = React.useState<FormPanelObject>();
  const [tabKey, setTabKey] = React.useState('1');
  const [showBorrowoutForm, setShowBorrowoutForm] = React.useState(false);
  const [selectDataType, setSelectDataType] = React.useState<Array<any>>([]);
  const [showApprove, setShowApprove] = React.useState<boolean>(false);
  const [curId, setCurId] = React.useState<number>(0);
  const [curTeacherId, setCurTeacherId] = React.useState<number>(0);
  const isSchool = Utils.getProps('isSchool');
  const country = useCountry();

  const template = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        { label: '教职工编码', name: 'teacher_code', key: 'teacher_code' },
        { label: '姓名', name: 'teacher_name', key: 'teacher_name' },
        {
          label: '状态',
          name: 'approval_status',
          key: 'approval_status',
          inputType: InputType.select,
          renderOption: APPROVAL_STATUS,
        },
        { label: '原任职单位', name: 'original_unit', key: 'original_unit' },
        {
          label: '原任职岗位',
          name: 'original_district_area_id',
          key: 'original_district_area_id',
          // renderOption: SY_ZONES,
          // inputType: InputType.select,
          inputType: InputType.cascader,
          renderOption: getProvinceCityCascader,
          formatSubmitValue: v => {
            if (!v) return [];
            return v[2];
          },
        },
        { label: '现任职单位', name: 'current_unit', key: 'current_unit' },
        {
          label: '现任职岗位',
          name: 'current_region_area_id',
          key: 'current_region_area_id',
          renderOption: country,
          inputType: InputType.select,
        },
        {
          label: '现单位行政所属地',
          name: 'current_region_area_id',
          key: 'current_region_area_id',
          //inputType: InputType.cascader,
          // renderOption: getProvinceCityCascader,
          // formatSubmitValue: v => {
          //   if (!v) return [];
          //   return v[2];
          // },
          renderOption: country,
          inputType: InputType.select,
        },
        {
          label: '发起时间',
          name: 'operation_time',
          key: 'operation_time',
          inputType: InputType.dateRange,
          formatSubmitValue: (value, formPanelObject: FormPanelObject) => {
            ExtendReader.formatSubmitValueByDateRange(value, formPanelObject, 'operation_time');
            return null;
          },
        },
        {
          label: '借出时间',
          name: 'approval_time',
          key: 'approval_time',
          inputType: InputType.dateRange,
          formatSubmitValue: (value, formPanelObject: FormPanelObject) => {
            ExtendReader.formatSubmitValueByDateRange(value, formPanelObject, 'approval_time');
            return null;
          },
        },
        // {
        //   label: '身份证件类型',
        //   name: 'teacher_id_type',
        //   key: 'teacher_id_type',
        //   inputType: InputType.select,
        //   relationFields: ['teacher_id_number'],
        //   renderOption: ID_TYPE,
        // },
        // {
        //   label: '身份证号码',
        //   name: 'teacher_id_number',
        //   key: 'teacher_id_number',
        //   ruleType: (formObjectPanel: FormPanelObject) => {
        //     const id_type = formObjectPanel.getFieldValue('teacher_id_type');
        //     if (id_type === 'resident_id_card') {
        //       return RuleType.cnPeopleNo;
        //     }
        //     return '';
        //   },
        // },
        // {
        //   label: '性别',
        //   name: 'teacher_gender',
        //   key: 'teacher_gender',
        //   inputType: InputType.select,
        //   renderOption: GENDER,
        // },
        // {
        //   label: '原任职单位管辖区',
        //   name: 'original_region_area_id',
        //   key: 'original_region_area_id',
        //   renderOption: country,
        //   inputType: InputType.select,
        // },
        // {
        //   label: '原任职单位行政区',
        //   name: 'original_district_area_id',
        //   key: 'original_district_area_id',
        //   renderOption: country,
        //   inputType: InputType.select,
        // },
        // { label: '原任职单位', name: 'original_unit', key: 'original_unit' },
        // { label: '现任职单位', name: 'current_unit', key: 'current_unit' },
        // {
        //   label: '现任职单位管辖区',
        //   name: 'current_region_area_id',
        //   key: 'current_region_area_id',
        //   inputType: InputType.cascader,
        //   renderOption: getProvinceCityCascader,
        //   formatSubmitValue: v => {
        //     if (!v) return [];
        //     return v[2];
        //   },
        // },
        // { label: '审批人', name: 'approval_name', key: 'approval_name' },
        // {
        //   label: '审批状态',
        //   name: 'approval_status',
        //   key: 'approval_status',
        //   inputType: InputType.select,
        //   renderOption: APPROVAL_STATUS,
        // },
        // {
        //   label: '申请时间',
        //   name: 'operation_time',
        //   key: 'operation_time',
        //   inputType: InputType.dateRange,
        //   formatSubmitValue: (value, formPanelObject: FormPanelObject) => {
        //     ExtendReader.formatSubmitValueByDateRange(value, formPanelObject, 'operation_time');
        //     return null;
        //   },
        // },
        // {
        //   label: '审批时间',
        //   name: 'approval_time',
        //   key: 'approval_time',
        //   inputType: InputType.dateRange,
        //   formatSubmitValue: (value, formPanelObject: FormPanelObject) => {
        //     ExtendReader.formatSubmitValueByDateRange(value, formPanelObject, 'approval_time');
        //     return null;
        //   },
        // },
      ],
    },
  ];
  const columns: TableProps['columns'] = [
    {
      title: '编号',
      dataIndex: 'teacher_id',
      width: 70,
      render: (text, record, index) => index + 1,
    },
    {
      title: '姓名',
      dataIndex: 'teacher_name',
      key: 'teacher_name',
      width: 150,
    },
    {
      title: '教职编码',
      dataIndex: 'teacher_number',
      key: 'teacher_number',
      width: 150,
    },
    {
      title: '原任职单位',
      dataIndex: 'original_unit_name',
      key: 'original_unit_name',
      width: 150,
    },
    {
      title: '原任职岗位',
      dataIndex: 'original_region_area_name',
      key: 'original_region_area_name',
      width: 200,
      render: (text, record) => {
        if (
          record.original_district_province_name &&
          record.original_district_city_name &&
          record.original_district_area_name
        )
          return `${record.original_district_province_name}/${record.original_district_city_name}/${record.original_district_area_name}`;
        return '/';
      },
    },
    {
      title: '现任职单位',
      dataIndex: 'current_unit_name',
      key: 'current_unit_name',
      width: 150,
    },
    {
      title: '现任职岗位',
      dataIndex: 'current_region_area_name',
      key: 'current_region_area_name',
      width: 150,
      render: (text, record) => {
        if (
          record.current_district_province_name &&
          record.current_district_city_name &&
          record.current_district_area_name
        )
          return `${record.current_district_province_name}/${record.current_district_city_name}/${record.current_district_area_name}`;
        return '/';
      },
    },
    {
      title: '现单位行政区所属地',
      dataIndex: 'current_district_area_name',
      key: 'current_district_area_name',
      render: (text, record) => {
        if (record.current_region_province_name && record.current_region_city_name && record.current_region_area_name)
          return `${record.current_region_province_name}/${record.current_region_city_name}/${record.current_region_area_name}`;
        return '/';
      },
    },
    {
      title: '状态',
      dataIndex: 'approval_status',
      key: 'approval_status',
      width: 150,
      render: (text: any) => {
        if (text) return _.find(APPROVAL_STATUS, { value: String(text) })?.label;
        return text;
      },
    },
    {
      title: '借出时间',
      dataIndex: 'start_time',
      key: 'start_time',
      width: 150,
      render: (text: any) => {
        if (!text) return '';
        return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '操作',
      dataIndex: 'operations',
      key: 'operations',
      //width: 300,
      fixed: 'right',
      align: 'center',
      // hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space size="middle">
          <Button
            type="link"
            onClick={() => {
              navigator(`${getPathRoot()}/alteration/borrowing/out/1`);
            }}
          >
            查看
          </Button>
          <PermissionButton permission="view">
            <Button
              type="link"
              onClick={() => {
                navigator(`${getPathRoot()}/alteration/borrowing/out/1`);
              }}
            >
              查看
            </Button>
          </PermissionButton>
          {['pending', 'progressing'].includes(record.approval_status) && (
            <PermissionButton permission="approval">
              <Button
                type="link"
                onClick={async () => {
                  setShowApprove(true);
                  setCurId(record.process_instance_id);
                  setCurTeacherId(record.teacher_id);
                }}
              >
                审核
              </Button>
            </PermissionButton>
          )}
          {['pending'].includes(record.approval_status) && (
            <PermissionButton permission="revoke">
              <Button
                type="link"
                onClick={async () => {
                  Modal.confirm({
                    title: '撤回',
                    content: `是否撤回${record.teacher_name}调出?`,
                    onOk: async () => {
                      const res = await borrowRevoked(record.process_instance_id, record.teacher_id);
                      if (res.success) {
                        message.success('撤回成功');
                      } else message.error(res.message || res.details);
                      searchFunc(pageIndex, pageIndex);
                    },
                  });
                }}
              >
                撤回
              </Button>
            </PermissionButton>
          )}
          {['revoked'].includes(record.approval_status) && (
            <PermissionButton permission="edit">
              <Button
                type="link"
                onClick={() => {
                  setSelectDataType([
                    {
                      teacher_id: record.teacher_id,
                      teacher_name: record.teacher_name,
                      teacher_id_number: record.teacher_id_number,
                      teacher_sub_status: record.teacher_sub_status,
                    },
                  ]);
                  setShowBorrowoutForm(true);
                  console.log('重新提交');
                }}
              >
                重新提交
              </Button>
            </PermissionButton>
          )}
        </Space>
      ),
    },
  ];
  const pageChange = (page: number, pageSize: number) => {
    set_stoge_pz(pageSize);
    searchFunc(page, pageSize);
  };

  const searchFunc = async (page: number, pageSize: number) => {
    setLoading(true);
    const searchval: SearchTransactionParams & PageParams = {
      ...(form ? form.getFieldsValue() : {}),
      page,
      per_page: pageSize,
    };
    let r;
    if (tabKey === '1') {
      r = await searchBorrowOutLaunch(searchval);
    } else {
      r = await searchBorrowOutApproval(searchval);
    }
    if (r.success) {
      setDataSource(r?.data?.items?.length > 0 ? r?.data?.items : [{ id: 0 }]);
      setTotal(r?.data?.total || 0);
      setPageIndex(page);
      setPageSize(pageSize);
    }
    setLoading(false);
  };

  React.useEffect(() => {
    searchFunc(pageIndex, pageSize);
  }, [tabKey]);

  return (
    // <PageContainer header={<Breadcrumb items={[{ title: '借出管理' }]} />}>
    <>
      <FormPanel
        btnsAlign={FormPanelBtnAlign.right}
        restBtnText="重置"
        submitBtnText="查询"
        template={template}
        onReset={form => {
          form.resetFields();
        }}
        onLoad={form => {
          setForm(form);
        }}
        onFinish={async (formPanelObject: FormPanelObject) => {
          searchFunc(pageIndex, pageSize);
        }}
      />
      {/* <Tabs
        defaultActiveKey="1"
        className={styles.tabs}
        type="card"
        items={[
          isSchool
            ? {
                label: '我发起',
                key: '1',
              }
            : {
                label: '我审批',
                key: '2',
              },
        ]}
        onChange={(key: string) => {
          setTabKey(key);
        }}
      /> */}
      <Space style={{ marginBottom: 20 }}>
        <Button type="primary" onClick={() => navigator(`${getPathRoot()}/alteration/borrowing/out/0`)}>
          发起借出
        </Button>
      </Space>
      <Table
        dataSource={dataSource}
        columns={columns}
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <BorrowPopup
        onFinish={() => searchFunc(pageIndex, pageSize)}
        showTransferoutForm={showBorrowoutForm}
        setShowTransferoutForm={setShowBorrowoutForm}
        selectDataType={selectDataType}
      />
      <Modal title="审批" open={showApprove} onCancel={() => setShowApprove(false)} footer={null}>
        <FormPanel
          template={[
            {
              title: '',
              span: 24,
              inputs: [
                {
                  label: '调动审核',
                  name: 'isApprove',
                  key: 'isApprove',
                  inputType: InputType.select,
                  renderOption: [
                    { label: '通过', value: 1 },
                    { label: '驳回', value: 2 },
                  ],
                },
                {
                  label: '审核说明',
                  name: 'approve_reason',
                  key: 'approve_reason',
                  inputType: InputType.textarea,
                },
              ],
            },
          ]}
          submitBtnText="确定"
          restBtnText="取消"
          buttonsDisplay={FormPanelBtnDisplay.block}
          btnsAlign={FormPanelBtnAlign.center}
          onReset={(formPanelObject: FormPanelObject) => {
            setShowApprove(false);
            formPanelObject.resetFields();
          }}
          onFinish={async (formPanelObject: FormPanelObject) => {
            const isApprove = formPanelObject.getFieldValue('isApprove');
            let res;
            if (isApprove === 1) {
              res = await transferApproved(curId, formPanelObject.getFieldValue('approve_reason'), curTeacherId);
            } else if (isApprove === 2) {
              res = await transferRejected(curId, formPanelObject.getFieldValue('approve_reason'), curTeacherId);
            }
            if (res?.success) {
              message.success('操作成功');
              searchFunc(pageIndex, pageSize);
              setShowApprove(false);
            } else {
              formPanelObject.reVaildation(res);
            }
          }}
        />
      </Modal>
    </>
  );
};

export default Groups;
